<template>
	<div class="system-goods-container layout-padding" style="height: 100%">
		<splitpanes class="default-theme" @resize="paneSize = $event[0].size">
			<pane :size="15">
				<div class="slider-content system-catalog-container">
					<el-card shadow="hover" class="layout-padding-auto">
						<div>
							<el-button @click="allCatalog" class="w100">全部商品</el-button>
						</div>
						<div>
							<el-tree
								:data="state.catalogData"
								:props="state.catalogProps"
								node-key="id"
								default-expand-all
								@node-click="onClickCatalog"
								:expand-on-click-node="false"
							>
							</el-tree>
						</div>
					</el-card>
				</div>
			</pane>
			<pane :size="85">
				<div class="standard-container system-goods-right-container padding">
					<div class="review-list-title">
						<div class="title-actions">
							<el-button size="default" type="primary" class="ml10" @click="handleSearchGoods">
								<el-icon>
									<ele-Search />
								</el-icon>
								查询
							</el-button>
							<el-button size="default" type="primary" class="ml10" @click="handleCreateItem">
								<el-icon>
									<ele-FolderAdd />
								</el-icon>
								新增商品
							</el-button>
							<el-button size="default" type="primary" class="ml10" @click="batchDeleteGoods">
								<el-icon>
									<ele-FolderAdd />
								</el-icon>
								批量删除
							</el-button>
							<el-button size="default" type="primary" class="ml10" @click="batchStatusGoods(1)">
								<el-icon>
									<ele-FolderAdd />
								</el-icon>
								商品上架
							</el-button>
							<el-button size="default" type="primary" class="ml10" @click="batchStatusGoods(0)">
								<el-icon>
									<ele-FolderAdd />
								</el-icon>
								商品下架
							</el-button>
							<!-- <el-form ref="tableSearchRef" size="default" :model="goodsSearchState" label-width="100px" class="table-form">
								<el-row>
									<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
										<el-form-item label="商品名称" prop="originaleName">
											<el-input size="default" placeholder="请输入商品名称" clearable style="width: 100%" v-model="goodsSearchState.originalName">
											</el-input>
										</el-form-item>
									</el-col>

									<el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
										<el-form-item label="商品状态" prop="status">
											<el-select v-model="goodsSearchState.status" clearable placeholder="请选择商品状态" style="width: 100%">
												<el-option label="未上架" :value="0" />
												<el-option label="已上架" :value="1" />
												<el-option label="已下架" :value="2" />
												<el-option label="隐藏" :value="3" />
											</el-select>
										</el-form-item>
									</el-col>

									<el-col :xs="24" :sm="12" :md="10" :lg="10" :xl="10">
										<el-form-item label="创建时间" prop="searchDateTime">
											<el-date-picker
												type="datetimerange"
												v-model="goodsSearchState.searchDateTime"
												start-placeholder="创建开始时间"
												end-placeholder="创建时间"
												style="width: 100%"
											/>
										</el-form-item>
									</el-col>

									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" :class="{ mt10: state.isToggle }">
										<el-form-item class="table-form-btn" label-width="10px">
		 
											<el-button size="default" type="primary" class="ml10" @click="handleSearchGoods">
												<el-icon>
													<ele-Search />
												</el-icon>
												查询
											</el-button>
											<el-button size="default" type="primary" class="ml10" @click="handleCreateItem">
												<el-icon>
													<ele-FolderAdd />
												</el-icon>
												新增商品
											</el-button>
											<el-button size="default" type="primary" class="ml10" @click="batchDeleteGoods">
												<el-icon>
													<ele-FolderAdd />
												</el-icon>
												批量删除
											</el-button>
											<el-button size="default" type="primary" class="ml10" @click="batchStatusGoods(1)">
												<el-icon>
													<ele-FolderAdd />
												</el-icon>
												商品上架
											</el-button>
											<el-button size="default" type="primary" class="ml10" @click="batchStatusGoods(0)">
												<el-icon>
													<ele-FolderAdd />
												</el-icon>
												商品下架
											</el-button>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form> -->
						</div>
					</div>
					<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%" @selection-change="handleSelectionGoods">
						<el-table-column type="selection" width="55" />

						<el-table-column label="商品名称" prop="title" width="120"> </el-table-column>

						<el-table-column label="商品图片" show-overflow-tooltip width="120">
							<template #default="scope">
								<el-image
									:src="scope.row.showPicUrl"
									fit="contain"
									class="image"
									:preview-src-list="[scope.row.showPicUrl]"
									:preview-teleported="true"
								></el-image>
							</template>
						</el-table-column>

						<el-table-column label="零售价格(元)" prop="price" width="120"> </el-table-column>

						<el-table-column label="原价格(元)" prop="originalPrice" width="100"> </el-table-column>

						<el-table-column label="库存" prop="stock" width="100"> </el-table-column>

						<el-table-column label="商品状态" show-overflow-tooltip width="150">
							<template #default="scope">
								<div class="select-status">
									<el-select v-model="scope.row.status" @change="updateStatus($event, scope.row.id)">
										<el-option label="未上架" :value="0" />
										<el-option label="已上架" :value="1" />
										<el-option label="已下架" :value="2" />
										<el-option label="隐藏" :value="3" />
									</el-select>
								</div>
								<!-- <el-tag v-if="scope.row.status == 1"> 已上架 </el-tag>
									<el-tag v-else-if="scope.row.status == 0">未上架</el-tag>
									<el-tag v-else-if="scope.row.status == 2">已下架</el-tag>
									<el-tag v-else type="warning">隐藏</el-tag> -->
							</template>
						</el-table-column>

						<el-table-column label="操作时间" prop="updateTime" width="200px"> </el-table-column>

						<el-table-column label="操作人" prop="updateUsername"> </el-table-column>

						<el-table-column label="操作" show-overflow-tooltip width="220" fixed="right">
							<template #default="scope">
								<el-button size="small" text type="primary" @click="onOpenGoods('edit', scope.row)">预览</el-button>
								<el-button size="small" text type="primary" @click="onOpenGoods('edit', scope.row)">修改</el-button>
								<el-button size="small" text type="primary" @click="onOpenGoods('delete', scope.row)">删除</el-button>
								<!-- <el-button size="small" text type="primary" @click="onOpenGoods('delete', scope.row)">上架</el-button>
              <el-button size="small" text type="primary" @click="onOpenGoods('delete', scope.row)">下架</el-button> -->
							</template>
						</el-table-column>
					</el-table>
					<div class="pagination-container">
						<el-pagination
							:pager-count="10"
							:page-sizes="[10, 20, 30, 50, 100]"
							v-model:current-page="state.tableData.paging.currentPage"
							background
							v-model:page-size="state.tableData.paging.pageSize"
							layout="total, sizes, prev, pager, next, jumper"
							:total="state.tableData.paging.totalCount"
						>
						</el-pagination>
					</div>
					<!-- </el-card> -->
				</div>
			</pane>
		</splitpanes>

		<ItemDialog ref="ItemDialogRef" @refresh="refresh"></ItemDialog>

		<!--		<el-popover ref="catalogPopoverRef" trigger="click" popper-class="custom-popper">-->
		<!--			<el-tabs class="demo-tabs" v-model="defaultTab" @tab-change="tabChange">-->
		<!--				<el-tab-pane :label="item.catalogName" :name="item.id" :key="item.id" v-for="item in state.catalogData">-->
		<!--					<el-cascader-panel :options="item.children" :props="state.catalogProps" @change="choiceCatalog" v-model="goodsSearchState.categoryIds">-->
		<!--					</el-cascader-panel>-->
		<!--				</el-tab-pane>-->
		<!--			</el-tabs>-->
		<!--		</el-popover>-->
	</div>
</template>

<script setup lang="ts" name="ShopGoods">
import { ElMessageBox } from 'element-plus';
import { goodsApi } from '/@/api/goods/index';
import { goodCatalogApi } from '/@/api/goods/catalog/index';
import msg from '/@/utils/messageUtils';
import { onMounted, reactive, ref, defineAsyncComponent, watch } from 'vue';
import _, { update } from 'lodash';
const catalogPopoverRef = ref();

import 'splitpanes/dist/splitpanes.css';

import { Splitpanes, Pane } from 'splitpanes';
const paneSize = ref(50);

const defaultTab = ref();
const ItemDialog = defineAsyncComponent(() => import('/@/views/goods/goods/itemDialog.vue'));

const ItemDialogRef = ref();

const state = reactive({
	catalogData: [] as any,
	isToggle: true,
	choiceIds: [],
	tableData: {
		data: [],
		total: 0,
		loading: false,
		paging: {
			currentPage: 1,
			pageSize: 10,
			totalCount: null,
			totalPages: null,
		},
	},
	search: {
		ids: [] as any,
	},
	choiceCatalogInfos: [] as ChoiceCatalogInfo[],
	choiceCatalogIds: [] as any,
	catalogProps: {
		multiple: true,
		label: 'catalogName',
		value: 'id',
		checkStrictly: true,
		emitPath: false,
		children: 'children',
	},
});

const goodsSearchState = reactive({
	originalName: '',
	categoryId: '',
	categoryIds: [] as any,
	status: '',
	startSearchDateTime: null,
	endSearchDateTime: null,
	searchDateTime: [],
});

// 商品分类  id 对应 名称
let mapCatalogInfo = new Map();

const onClickCatalog = (node: any) => {
	console.log('node: ', node);
	if (goodsSearchState.categoryId != node.id) {
		goodsSearchState.categoryId = node.id;
		onHandleCurrentChange(1);
	}
};

const allCatalog = () => {
	if (goodsSearchState.categoryId != '') {
		goodsSearchState.categoryId = '';
		onHandleCurrentChange(1);
	}
};

const onLoadCatalogData = async () => {
	try {
		const { data } = await goodCatalogApi().all();
		console.log('all.....: ', data);
		defaultTab.value = data[0].id;
		data.forEach((element: any) => {
			setMapCatalogIdAndName(element.children);
		});
		console.log('defaultTab.value: ', defaultTab.value);
		state.catalogData = data;
	} catch (error) {
		console.log(error);
		msg().error('获取分类父分类失败');
	}
};

const setMapCatalogIdAndName = (obj: any) => {
	obj.forEach((e: any) => {
		mapCatalogInfo.set(e.id, e.catalogName);
		if (!_.isEmpty(e.children)) {
			setMapCatalogIdAndName(e.children);
		}
	});
};

const handleSelectionGoods = (choiceIds: any) => {
	state.choiceIds = [];
	choiceIds.forEach((e: any) => state.choiceIds.push(e.id));
};

const handleSearchGoods = () => {
	const st: any = goodsSearchState.searchDateTime;
	if (st != null && st.length > 0) {
		goodsSearchState.startSearchDateTime = st[0].getTime();
		goodsSearchState.endSearchDateTime = st[1].getTime();
	} else {
		goodsSearchState.startSearchDateTime = null;
		goodsSearchState.endSearchDateTime = null;
	}
	onHandleCurrentChange(1);
};

const handleCreateItem = () => {
	ItemDialogRef.value.onOpenDialog('add', '');
};

const updateStatus = async (status: number, id: any) => {
	console.log('status: ', status, ' , row: ', id);
	try {
		await goodsApi().updateGoodsStatus({ id: id, status: status });
	} catch (error) {
		console.log(error);
		msg().error('修改状态失败,请稍后重试');
	}
};

const batchStatusGoods = async (status: number) => {
	if (state.choiceIds.length == 0) {
		msg().warn('请至少选中一个');
		return;
	}
	try {
		await goodsApi().batchGoodsStatus({ ids: state.choiceIds, status: status });
		refresh();
	} catch (error) {
		console.log(error);
		msg().error('批量修改状态失败,请稍后重试');
	}
};
const batchDeleteGoods = () => {
	if (state.choiceIds.length == 0) {
		msg().warn('请至少选中一个');
		return;
	}
	ElMessageBox.confirm(`此操作将永久删除选中的商品，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await goodsApi().batchDelete({ ids: state.choiceIds });
				msg().success('批量删除成功');
				onHandleCurrentChange(1);
			} catch (error: any) {
				msg().error(error.msg);
			}
		})
		.catch(() => {});
};

const onOpenGoods = (type: string, row: any) => {
	if (type === 'delete') {
		ElMessageBox.confirm(`此操作将永久删除商品："${row.title}"，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(async () => {
			try {
				await goodsApi().delete(row.id);
				msg().success('删除成功');
				onHandleCurrentChange(1);
			} catch (error) {
				msg().error('商品删除失败');
			}
		});
	} else {
		ItemDialogRef.value.onOpenDialog(type, row.id);
	}
};

watch(
	() => state.tableData.paging.currentPage,
	(newV, oldv) => {
		console.log(`currentPage, newV: ${newV}, oldV : ${oldv}`);
		onHandleCurrentChange(newV);
	}
);

watch(
	() => state.tableData.paging.pageSize,
	(newV, oldv) => {
		console.log(`pageSize, newV: ${newV}, oldV : ${oldv}`);
		onHandleSizeChange(newV);
	}
);

const refresh = () => {
	onHandleCurrentChange(1);
};

const onHandleSizeChange = (val: number) => {
	state.tableData.paging.pageSize = val;
	state.tableData.paging.currentPage = 1;
	getTableData();
};

const onHandleCurrentChange = (val: number) => {
	state.tableData.paging.currentPage = val;
	getTableData();
};

const updateGoodsStatus = async (obj: any, sale: number) => {
	console.log('obj: ', JSON.stringify(obj));

	console.log('sale:  ', sale);
	try {
		let { data } = await goodsApi().updateGoodsStatus({
			id: obj.id,
			isOnSale: sale,
		});
		obj.isOnSale = sale;
	} catch (error) {
		msg().error('修改失败，请重新操作！');
	}
};

const getCatalogIds = () => {
	if (goodsSearchState.categoryId != '') {
		return [goodsSearchState.categoryId];
	}
	return [];
};

const getTableData = async () => {
	try {
		const { data } = await goodsApi().search({
			categoryId: goodsSearchState.categoryId,
			searchStartTime: goodsSearchState.startSearchDateTime,
			searchEndTime: goodsSearchState.endSearchDateTime,
			goodsName: goodsSearchState.originalName,
			status: goodsSearchState.status,
			catalogIds: getCatalogIds(),
			offset: (state.tableData.paging.currentPage - 1) * state.tableData.paging.pageSize,
			limit: state.tableData.paging.pageSize,
		});
		state.tableData.data = data.datas;
		state.tableData.paging.currentPage = data.paging.currentPage;
		state.tableData.paging.totalCount = data.paging.totalCount;
		console.log('data： ', data);
	} catch (error) {
		msg().error('查询商品列表失败，请稍后重试');
	}
	state.tableData.loading = false;
};

onMounted(() => {
	getTableData();
	onLoadCatalogData();
});
</script>

<style scoped lang="scss">
.category-tag-wrap {
	flex: 1;
	min-height: 32px;
	//padding-right: 12px;
	border-radius: 4px;
	border: 1px solid #d9d9d9;
	cursor: pointer;
	position: relative;
	//padding-left: 10px;
	//padding-top: 8px;
	//padding-left: 12px;
	// padding: 8px 12px;
}

.category-tag-wrap-suffix {
	width: 12px;
	height: 100%;
	position: absolute;
	right: 6px;
	top: 0;
	display: flex;
	align-items: center;
	justify-content: center;
}

.el-popper.custom-popper {
	min-width: unset;
	width: fit-content !important;
}

.goods-content-container {
	height: 100%;
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}
}

.system-goods-container {
	// padding: 15px !important;
	overflow: hidden;
	height: calc(100vh - 84px);
	.system-catalog-container {
		height: 100%;
		:deep(.el-card__body) {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: auto;
			// margin: 15px 15px 40px 15px;
			// padding: 0px;
		}
		:deep(.el-tree-node__content) {
			// display: block !important;
		}
	}
}

.select-status {
	:deep(.el-select__wrapper) {
		padding: 4px 12px;
	}
}

.system-goods-right-container {
	// padding: 15px;
	display: flex;
	height: 100%;
	flex-direction: column;
	.el-table {
		flex: 1;
	}
}
</style>
